(function($) {
  $.fn.extend({
    draw: function(option) {
      if (!option) {
        option = {};
      }
      option = $.extend({}, $.fn.draw.defaultOption, option);
      try {
        if (
          !(option.colors instanceof Array) ||
          !(option.text instanceof Array)
        ) {
          throw Error("colors、text 接受的参数是 Array[string]");
        }
      } catch (e) {
        console.log(e.stack);
      }
      var that = $(this);
      try {
        var width = $(that).width(),
          height = $(that).height();
        if (!(width && height)) {
          throw Error("请设置宽高度");
        }
      } catch (e) {
        console.log(e.stack);
      }
      $(that).append(
        "<canvas width=" + width + " height=" + height + "></canvas>"
      );
      $(that).append(
        '<div class="mouse-hover" style="position: absolute;left:0;top:0;padding:5px;border-radius:4px;background:#000001;opacity:0.7;filter: opacity(0.7); ' +
          'color: #fffffe;display:none;transition:all 0.4s cubic-bezier(0.23,1,0.32,1) 0s;">火狐：36%</div>'
      );
      var obj = $(that).find("canvas")[0];
      ctx = obj.getContext("2d");
      obj.addEventListener(
        "mousemove",
        function(ev) {
          $.fn.draw.circular.addMouseEv(obj, ev || window.event, option.weight);
        },
        false
      );
      var circularIndex = 0,
        loopIndex = 0;
      /**
       * 根据需求默认画一个中心圆，
       */
      $.fn.draw.circular.begin(
        Math.floor(obj.clientWidth / 2),
        Math.floor(obj.clientHeight / 2),
        Math.floor(obj.clientHeight / 5),
        option.text[0],
        option.colors[0],
        ctx
      );
      // 获取中心点的坐标和半径 x1 , y1 , r1;
      try {
        while (true) {
          circularIndex++;
          // 寻找0 - ?  之间的数值
          var x = Math.floor(Math.random() * width),
            y = Math.floor(Math.random() * height);
          var cir = $.fn.draw.circular.effect(x, y, width, height);
          if (circularIndex >= option.number) {
            // 随机生成10个园
            break;
          }
          if (!cir) {
            circularIndex--;
            loopIndex++;
            if (loopIndex > 500000) {
              // 如果循环4000+ 还没有找到合适的圆，停止，防止死循环
              break;
            }
            continue;
          } else {
            var color = option.colors[circularIndex]
              ? option.colors[circularIndex]
              : option.colors[circularIndex % option.colors.length];
            var text = option.text[circularIndex]
              ? option.text[circularIndex]
              : option.text[circularIndex % option.text.length];
            $.fn.draw.circular.begin(cir.x, cir.y, cir.r, text, color, ctx);
          }
        }
      } catch (e) {
        console.log(e);
      }
    },
    clearArray:function(){
      $.fn.draw.circular.clearCanvas();
    }
  });
})(jQuery);
(function($) {
  var recordArr = [];
  $.fn.draw.defaultOption = {
    number: 5, // 生成的个数
    colors: ["#FF8E56"], // 默认一个颜色，可以接受的参数是 Array
    text: ["Chrome"],
    weight: ["100%"]
  };
  $.fn.draw.circular = {
    /**
          x1  x轴坐标
          y   y轴坐标
          r   半径
          text 文字
          color 填充颜色
        **/
    begin: function(x, y, r, text, color, ctx) {
      recordArr.push({
        x: x,
        y: y,
        r: r
      });
      ctx.beginPath();
      ctx.arc(x, y, r, 0, 2 * Math.PI, false);
      ctx.fillStyle = color;
      ctx.fill();
      ctx.font = "14px Microsoft YaHei";
      ctx.fillStyle = "#fffffe";
      ctx.textAlign = "center";
      ctx.fillText(text, x, y + 5);
      ctx.closePath();
    },
    /**
     * 寻找合适的 x , y , r。
     * x 坐标
     * y 坐标
     * width 当前盒子宽度
     * height 盒子高度
     *  */
    effect: function(x, y, width, height) {
      // 设置一个以盒子大小来计算的半径
      var boxR = Math.floor(width / 6);
      // 获取随机半径
      var randomR = Math.floor(Math.random() * boxR);
      if (randomR < 30) {
        // 设置半径不能低于30
        return false;
      } else {
        // 不能划到框外
        if (x + randomR > width || y + randomR > height) {
          return false;
        } else if (y - 2 * randomR < 0 || x - 2 * randomR < 0) {
          return false;
        }
        // 不能出现重叠圆
        for (var a = 0; a < recordArr.length; a++) {
          var distant = Math.floor(
            Math.sqrt(
              Math.pow(Math.abs(recordArr[a].x - x), 2) +
                Math.pow(Math.abs(recordArr[a].y - y), 2)
            )
          );
          if (distant < randomR + recordArr[a].r) {
            return false;
          }
        }
        return {
          x: x,
          y: y,
          r: randomR
        };
      }
    },
    /**
     * 添加鼠标hover 事件
     * @params canvas 对象
     * @params ev 鼠标在盒子内移动对象
     * @params weight 占比
     */
    addMouseEv: function(ctx, ev, percent) {
      var mousePos = $.fn.draw.circular.getMousePos(ctx, ev);
      var pagex = mousePos.x,
        pagey = mousePos.y,
        circelHover = null;
      for (
        var isCircle = 0, len = recordArr.length;
        isCircle < len;
        isCircle++
      ) {
        circelHover = $.fn.draw.circular.getPixel(
          recordArr[isCircle],
          pagex,
          pagey
        );
        if (circelHover) {
          $(ctx)
            .parent()
            .css({
              cursor: "pointer"
            });
          $(ctx)
            .next()
            .css({
              display: "block",
              left: pagex + 10 + "px",
              top: pagey + 10 + "px"
            })
            .html(
              "浏览器使用情况：" + (percent[isCircle % percent.length] || "0%")
            );
          return false;
        } else {
          $(ctx)
            .parent()
            .css({
              cursor: "auto"
            });
          $(ctx)
            .next()
            .hide();
        }
      }
    },
    /**
     * 获取鼠标在canvas画布上的位置
     */
    getMousePos: function(ctx, evt) {
      var rect = ctx.getBoundingClientRect();
      return {
        x: Math.floor(evt.clientX - rect.left * (ctx.width / rect.width)),
        y: Math.floor(evt.clientY - rect.top * (ctx.height / rect.height))
      };
    },
    /**
     * 判断移动的是否在圆内
     * @params 当前圆的坐标
     * @params 鼠标移动 x
     * @params 鼠标移动 y
     */
    getPixel: function(coordinate, mouseX, mouseY) {
      var newX = Math.abs(coordinate.x - mouseX),
        newY = Math.abs(coordinate.y - mouseY);
      diff = Math.sqrt(Math.pow(newX, 2) + Math.pow(newY, 2));
      return diff - coordinate.r <= 0 ? true : false;
    },
    clearCanvas: function() {
      recordArr = [];
    }
  };
})(jQuery);
